package com.asktgapp.engineer.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.ChooseBankFragment;
import com.asktgapp.dialog.WithdrawDiolog;
import com.asktgapp.engineer.activity.ApplyForMoenySuccessActivity;
import com.asktgapp.engineer.activity.IDVerificationActivity;
import com.asktgapp.engineer.activity.WithDrawRecordActivity;
import com.asktgapp.model.BalanceVO;
import com.asktgapp.model.BankVO;
import com.asktgapp.model.LawVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/25
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:申请提现fragment
 */

public class ApplyForMoenyFragment extends BaseFragment {

    @InjectView(R.id.et_moeny)
    EditText mMoeny;//提现的金额数
    @InjectView(R.id.rl_alipay)
    RelativeLayout mAlipayRl;
    @InjectView(R.id.rl_unionpay)
    RelativeLayout mUnionpayRl;
    @InjectView(R.id.cb_alipay)
    CheckBox mAlipayCb;
    @InjectView(R.id.cb_unionpay)
    CheckBox mUnionpayCb;
    @InjectView(R.id.et_account)
    EditText mAccount;
    @InjectView(R.id.ll_back_type)
    LinearLayout mBankTypeLl;
    @InjectView(R.id.tv_bank_type)
    TextView mBankTypeChoose;
    @InjectView(R.id.tv_commit)
    TextView mCommit;
    @InjectView(R.id.tv_tx_fee)
    TextView mTXFee;

    BalanceVO bean;
    List<BankVO> mBankList;
    private String TaxFee;
    private int limit;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_with_draw, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    protected void initView(View rootView) {
        setHasOptionsMenu(true);
        getBaseActivity().setBackNavigationIcon();
        mAlipayRl.setOnClickListener(this);
        mUnionpayRl.setOnClickListener(this);
        mBankTypeChoose.setOnClickListener(this);
        mCommit.setOnClickListener(this);

    }

    @Override
    public void loadData() {

//        showProgress(getClass().getSimpleName());
        visibleLoading();
        //// TODO: 2018/1/25 调用接口获取当前提现的最大金额数
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<BalanceVO>> call = apiservice.getProjecterMoney(params);
        call.enqueue(new Callback<ApiResponseBody<BalanceVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<BalanceVO>> call, Response<ApiResponseBody<BalanceVO>> response) {
                inVisibleLoading();
//                dismissProgress();
                if (response.isSuccessful()) {
                    dismissProgress();
                    bean = response.body().getResult();
                    mMoeny.setHint("最多可输入" + String.valueOf(bean.getMoney()));
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<BalanceVO>> call, Throwable t) {
                inVisibleLoading();
//                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
        HashMap map = new HashMap();
        Call<ApiResponseBody<List<BankVO>>> bank = apiservice.findBankList(map);
        bank.enqueue(new Callback<ApiResponseBody<List<BankVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<BankVO>>> call, Response<ApiResponseBody<List<BankVO>>> response) {
//                dismissProgress();
                if (response.isSuccessful()) {
                    mBankList = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<BankVO>>> call, Throwable t) {
//                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });

        final Call<ApiResponseBody> fee = apiservice.getTixianShouxu(params);
        fee.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
//                dismissProgress();
                if (response.isSuccessful()) {
                    TaxFee = (String) response.body().getResult();
                    if (!Util.isEmpty(TaxFee)) {
                        double tax = Double.valueOf(TaxFee);
                        DecimalFormat df = new DecimalFormat("0.0%");
                        mTXFee.setVisibility(View.VISIBLE);
                        mTXFee.setText("本次提现将扣除" + df.format(tax) + " 的手续费");
                    } else mTXFee.setVisibility(View.GONE);
                } else {
                    showTost(response.raw().message(), 0);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
//                dismissProgress();

            }
        });
        params.put("type", 9);
        Call<ApiResponseBody<LawVO>> call1 = apiservice.xieyiInfo(params);
        call1.enqueue(new Callback<ApiResponseBody<LawVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<LawVO>> call, Response<ApiResponseBody<LawVO>> response) {
                if (response.isSuccessful()) {
                    LawVO mLawVO = response.body().getResult();
                    if (!Util.isEmpty(mLawVO.getContent())) {
                        limit = Integer.parseInt(mLawVO.getContent());
                    }
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<LawVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_alipay:
                mAlipayCb.setChecked(true);
                mUnionpayCb.setChecked(false);
                mAccount.setHint("请输入您的支付宝账号");
                mBankTypeLl.setVisibility(View.GONE);
                break;
            case R.id.rl_unionpay:
                mAlipayCb.setChecked(false);
                mUnionpayCb.setChecked(true);
                mAccount.setHint("请输入您的银行卡账号");
                mBankTypeLl.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_bank_type:
                //弹出底部wheelview，选择银行，等接口对象出来后再写
                ChooseBankFragment chooseBankFragment = new ChooseBankFragment(new ChooseBankFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mBankTypeChoose.setText(s[0]);
                    }
                }, mBankList, "请选择银行类型");
                chooseBankFragment.show(getFragmentManager(), "chooseBankFragment");

                break;
            case R.id.tv_commit:
                hideSoftKeyboard();
                if (Util.isEmpty(mMoeny.getText().toString())) {
                    showTost("请输入提现金额", 1);
                    return;
                }
                if (Double.valueOf(mMoeny.getText().toString().trim()) < 100) {
                    showTost("提现金额必须大于100元", 0);
                    return;
                }
                if (mUnionpayCb.isChecked()) {
                    if (Util.isEmpty(mBankTypeChoose.getText().toString())) {
                        showTost("请选择银行类型", 1);
                        return;
                    }
                }
                if (Util.isEmpty(mAccount.getText().toString())) {
                    showTost("请输入账号", 1);
                    return;
                }
                if (mAccount.getText().toString().length() < 11) {
                    showTost("请输入合法长度的账号", 1);
                    return;
                }


                //没有提现密码，要前往设置
                if (bean.getHasTixianPwd() == 0) {
                    startActivity(new Intent(getActivity(), IDVerificationActivity.class));
                } else {
                    //需要判断是不是首次提现，首次提现需要跳转到设置密码的界面
                    WithdrawDiolog withdrawDiolog = new WithdrawDiolog(new WithdrawDiolog.onResult() {
                        @Override
                        public void onSuccess(String s) {
                            tx(s);
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    withdrawDiolog.show(getFragmentManager(), "WithdrawDiolog");
                }

                break;
        }
    }

    private void tx(String s) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("money", mMoeny.getText().toString());
        if (Integer.parseInt(mMoeny.getText().toString().trim()) < limit) {
            showTost("提现金额不得低于" + limit + "元", 1);
            return;
        }
        params.put("account", mAccount.getText().toString());
        params.put("tiXianPwd", s);
        //提现方式0:支付宝 1:银行卡
        if (mAlipayCb.isChecked()) {
            params.put("type", 0);
        } else {
            params.put("type", 1);
            params.put("bank_name", mBankTypeChoose.getText().toString());
        }
        Call<ApiResponseBody> call = apiservice.tiXian(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                if (response.isSuccessful()) {
                    startActivity(new Intent(getActivity(), ApplyForMoenySuccessActivity.class));
                    getActivity().finish();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.withdraw_record, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        startActivity(new Intent(getActivity(), WithDrawRecordActivity.class));
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }
}
